﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace zielonka.co.uk.extensions.system.data
{
    // Description: Use the Get[Type] functions that are part of the IDataReader but by passing the field name as a string as opposed to the field ordinal as int. Allows assigning default values for null values returned by the datareader.
    /*
        var itemID = datareader.GetInt32("ItemID");

        //With Default

        var ItemName = datareader.GetString("ItemName", "Unknown");
    */


    // A set of extension methods for IDataReader
    public static partial class DataReaderExtensions
    {
        /// <summary>
        /// This method extends the GetBoolean method of the data reader to allow calling by the field name
        /// </summary>
        /// <param name="dataReader">The datareader object we are extending</param>
        /// <param name="fieldName">The field name that we are getting the Boolean value for</param>
        /// <returns></returns>
        public static bool GetBoolean(this IDataReader dataReader, string fieldName)
        {
            var fieldOrdinal = dataReader.GetOrdinal(fieldName);
            var retVal = false;

            if (!dataReader.IsDBNull(fieldOrdinal))
            {
                try
                {
                    retVal = dataReader.GetBoolean(fieldOrdinal);
                }
                catch (InvalidCastException)
                {
                    //We will swallow this exception as it's expected if our value has a dataType of bit. 
                    //We will try and handle that by casting to an Int16.
                    //If it fails here, we will allow the exception to get thrown
                    return (dataReader.GetInt16(fieldOrdinal) == 1);
                }

            }

            return retVal;
        }
    }
}
